/*
 * 创建日期 2009-12-15
 *
 * 成都天和软件公司
 * 电话：028-85425861
 * 传真：028-85425861-8008
 * 邮编：610041 
 * 版权所有
 */
package  org.fantasy.common.grid.custom;

import  org.fantasy.common.db.bean.Row;
import  org.fantasy.common.grid.bean.Column;
import  org.fantasy.common.util.ExpressionUtil;
import  org.fantasy.common.util.NumberUtil;
import  org.fantasy.common.util.StringUtil;

import java.math.BigDecimal;
import java.util.List;

/**
 * 单元格基本装饰方式
 * @author: 王文成
 * @version: 1.0
 * @since 2009-12-15
 */
public class BaseCustomSupport extends AbstractCustom implements CellCustom{

    public String getClassName(Row row, Column col)  throws Exception{
        return "";
    }

    public String getStyle(Row row, Column col)  throws Exception{
        return "";
    }

    public String getValue(Row row, Column col) throws Exception{
        String value = null;
        // 如果是表达式
        if (col.isExpressionType()) {
            BigDecimal fieldValue = eval(col.getExpression(), row, col.getExpParams());
            int scale = col.isPercentType() ? 4 : 2;
            BigDecimal decimal = fieldValue.setScale(col.getScale(scale), BigDecimal.ROUND_HALF_UP);
            value = String.valueOf(decimal);
        } else {
            value = row.getCell(col.getFieldName()).getString();
        }

        if (col.isPercentType())
            return NumberUtil.getPercentNumber(value);
        else if (col.isCommaType())
            return NumberUtil.getCommaNumber(value);
        else
            return value;
    }
    
    protected BigDecimal eval(String expression, Row row, List<String> params) throws Exception {
        for (String param : params) {
            String value = row.getCell(param).getString();
            if (!StringUtil.isValid(value)) {
                value = "0";
            }
            expression = expression.replaceAll("#" + param + "#", "(" + value + "d)");
        }
        return ExpressionUtil.eval(expression);
    }
}
